package indi.zhifa.core.dataauth.sqlHelper;

import indi.zhifa.core.dataauth.sqlHelper.sqlNode.NormalSqlPhase;
import indi.zhifa.core.dataauth.sqlHelper.sqlNode.SqlAnalysisNode;
import indi.zhifa.core.dataauth.sqlHelper.sqlNode.VarSqlPhase;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.ASTNodeAccessImpl;

import java.util.ArrayList;
import java.util.List;

public class SqlAnalyseHolder {

    private List<SqlAnalysisNode> mSqlAnalysisNodeList;
    private ISqlVarProvider mSqlVarProvider;

    public SqlAnalyseHolder(ISqlVarProvider pSqlVarProvider){
        mSqlVarProvider = pSqlVarProvider;
    }

    public void analyse(String pSql){
        mSqlAnalysisNodeList = new ArrayList<>();
        SqlAnalysisNode begNode = new NormalSqlPhase();
        mSqlAnalysisNodeList.add(begNode);
        SqlAnalysisNode curNode = begNode;

        for(char c : pSql.toCharArray()){
            SqlAnalysisNode newNode = curNode.addChar(c);
            if(null != newNode){
                curNode = newNode;
                mSqlAnalysisNodeList.add(newNode);
            }
        }
    }

    public String getSql(){
        StringBuilder sb = new StringBuilder();
        for(SqlAnalysisNode node : mSqlAnalysisNodeList){
            if(node instanceof NormalSqlPhase){
                String sql = node.toSql();
                sb.append(sql);
            }else if(node instanceof VarSqlPhase){
                String varName = node.toSql();
                Expression expression = mSqlVarProvider.getVar(varName);
                sb.append(expression);
            }
            sb.append(" ");
        }
        return sb.toString();
    }

}
